package com.example.mytestapp;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mytestapp.testvideoplayer.TestVieoPlayActivity;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends Activity implements EasyPermissions.PermissionCallbacks{
    private Button generateBtn = null;
    private EditText editText = null;
    private ImageView imageView = null;
    private TextView textView = null;
    private String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.INTERNET};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        generateBtn = findViewById(R.id.btn);
        editText = findViewById(R.id.edit);
        imageView = findViewById(R.id.img);
        textView = findViewById(R.id.text);
        if (Build.VERSION.SDK_INT >= 23) {

            if (EasyPermissions.hasPermissions(MainActivity.this, mPermissionList)) {
            } else {
                EasyPermissions.requestPermissions(this, "存储二维码需要的权限", 1, mPermissionList);
            }
        } else {
        }

        generateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(editText.getText().toString())){
                    Bitmap bitmap = generateBitmap(editText.getText().toString(),500,500);
                    imageView.setImageBitmap(bitmap);
                    File folder = new File(Environment.getExternalStorageDirectory()+File.separator+"QRCode");
                    if(!folder.exists()){
                        folder.mkdirs();
                    }
                    File bitmapFile = new File(Environment.getExternalStorageDirectory()+File.separator+"QRCode"+File.separator+new Date().getTime()+".jpg");
                    try {
                        bitmapFile.createNewFile();
                        FileOutputStream fileOutputStream = new FileOutputStream(bitmapFile);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
                        fileOutputStream.flush();
                        fileOutputStream.close();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    textView.setText("二维码保存路径为 "+bitmapFile.getAbsolutePath());
                    Uri uri = Uri.fromFile(bitmapFile);
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                    intent.setType("image/jpeg");
                    startActivity(Intent.createChooser(intent, "分享"));


                    ToastUtil.showShort(MainActivity.this,"保存二维码成功，快去分享给朋友吧！");
                }else{
                    ToastUtil.showShort(MainActivity.this,"您还没有输入文字！");
                   // Toast.makeText(MainActivity.this,"您还没有输入文字！",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private Bitmap generateBitmap(String content, int width, int height) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN){
            switch (keyCode){
                case KeyEvent.KEYCODE_0:
                    Intent intent = new Intent(MainActivity.this, TestVieoPlayActivity.class);
                    startActivity(intent);
                    finish();
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
